package spark.network;

import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.net.InetAddress;

import spark.network.protocol.Base;
import spark.network.IConnections;
import spark.network.NetworkConnection;
import spark.network.protocol.PreLoginResponse;

public class ServerConnection implements IConnections {
	private static Logger logger = Logger.getLogger(ServerConnection.class);

	private NetworkConnection server;

	public ServerConnection(InetAddress serverAddress, int serverPort) {
		server = new NetworkConnection();
		server.setResponseAddress(new InetSocketAddress(serverAddress, serverPort));
	}

	@Override
	public boolean isValid(InetSocketAddress source, Base packet) {
		// if no connection has been established yet we validate the packet
		if(server.getSession() == NetworkConnection.SESSION_UNESTABLISHED) {
			return true;
		}
		//if the server sent the wrong session he is denied
		if(server.getSession() != packet.getSession()) {
			return false;
		}
		//if the right session was sent but from a different address+port than is known to us don't accept
		return server.getAddress().equals(source);
	}

	@Override
	public NetworkConnection getConnection(long session) {
		//if the session that was provided matches that of our server session we are ok
		if( server.getSession() == session  ||
		//else if the session has not yet been established (prelogin) we return the server still
			server.getSession() == NetworkConnection.SESSION_UNESTABLISHED	) {
			return server;
		}
		return null;
	}

	public void reset() {
		InetSocketAddress serverQueryAddress = server.getResponseAddress();
		server.reset();
		server.setResponseAddress(serverQueryAddress);
	}

	public NetworkConnection getServerConnection() {
		return server;
	}
}